import qs from 'qs'
import { base64Decode, securityEncrypt } from "@/utils/crypto"
import { _ACCESS_TOKEN } from '@/config/constant'

export type CustomRequestOptions = UniApp.RequestOptions & {
  query?: Record<string, any>
} & IUniUploadFileOptions

// 请求基地址
const baseURL = import.meta.env.VITE_BASE_URL

// 拦截器配置
const httpInterceptor = {
  // 拦截前触发
  invoke(options: CustomRequestOptions) {
    // 接口请求支持通过 query 参数配置 queryString
    const originUrl = options.url
    if (options.query) {
      const queryStr = qs.stringify(options.query)
      if (options.url.includes('?')) {
        options.url += `&${queryStr}`
      } else {
        options.url += `?${queryStr}`
      }
    }

    // 非 http 开头需拼接地址
    if (!options.url.startsWith('http')) {
      options.url = baseURL + options.url
    }
    // 请求超时
    options.timeout = 12000 
    
    // 添加 Security 请求头
    // options.header.Security = securityEncrypt(originUrl || '')
    
    // 添加 Authorization 请求头
    const storageAccessToken = uni.getStorageSync(_ACCESS_TOKEN)
    if (storageAccessToken) {
      options.header.Authorization = `Bearer ${base64Decode(storageAccessToken)}`
    }
  },
}

export const requestInterceptor = {
  install() {
    uni.addInterceptor('request', httpInterceptor)
    uni.addInterceptor('uploadFile', httpInterceptor)
  },
}
